package api

import (
	"cgs-server/helper"
	"cgs-server/server"
	"cgs-server/server/base"
	"cgs-server/server/cgs/app/models/dto"
	"cgs-server/server/cgs/app/service"
	"cgs-server/server/cgs/app/store"
	"mime/multipart"
	"net/http"
	"strconv"
)

type AppHandler struct {
	// srv service
	srv service.Service
	// store
	store store.Factory
}

func NewAppHandler(store store.Factory) *AppHandler {
	srv := service.NewService(store)
	return &AppHandler{
		srv:   srv,
		store: store,
	}
}

func (app *AppHandler) Get(w http.ResponseWriter, r *http.Request) {
	appId := r.FormValue("id")
	if appId == "" {
		_, _ = helper.WriteJSON(w, server.Fail("app id is required"))
		return
	}
	//getWorksheetInfo := r.FormValue("getWorksheetInfo") == "true"
	getWorksheetInfo, _ := strconv.ParseBool(r.FormValue("getWorksheetInfo"))

	user, err := base.GetCurrentUser(r)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	appData, err := app.srv.App().Get(appId, getWorksheetInfo, true, user)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK().WithData(appData))
}

func (app *AppHandler) Update(w http.ResponseWriter, r *http.Request) {
	var app2 dto.App
	err := helper.ReadRequestBody(&app2, w, r)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	user, err := base.GetCurrentUser(r)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	err = app.srv.App().Update(&app2, user)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK())
}

func (app *AppHandler) Export(w http.ResponseWriter, r *http.Request) {
	appId := r.FormValue("id")
	if appId == "" {
		_, _ = helper.WriteJSON(w, server.Fail("app id is required"))
		return
	}
	user, err := base.GetCurrentUser(r)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	appData, err := app.srv.App().Export(appId, user)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	buf, err := base.ZipFile(appData)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	head := w.Header()
	head.Set("Content-Disposition", "attachment; filename=CGSApp.zip")
	_, _ = buf.WriteTo(w)
}

func (app *AppHandler) Import(w http.ResponseWriter, r *http.Request) {
	_ = r.ParseMultipartForm(100 << 20)
	var file *multipart.FileHeader
	files := r.MultipartForm.File
	if f, ok := files["file"]; ok {
		if len(f) > 0 {
			file = f[0]
		}
	}
	category := r.FormValue("category")
	filePath := r.FormValue("filePath")

	user, err := base.GetCurrentUser(r)
	if user == nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
	}

	if err := app.srv.App().Import(file, category, filePath, user); err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK())
}
